﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using ThresholdAssistant.ConfigSdk.Constants;
using System;
using System.Collections.Generic;

namespace ThresholdAssistant.ConfigSdk
{
    /// <summary>
    /// 配置文件信息
    /// </summary>
    public static class AppJson
    {
        /// <summary>
        /// 文件路径（默认：根目录）
        /// </summary>
        public static string FileDir = null;

        /// <summary>
        /// 文件名称
        /// </summary>
        public static string FileName = "appsettings.json";

        /// <summary>
        /// 配置文件信息
        /// </summary>
        public static IConfiguration Configuration { get; set; }

        /// <summary>
        /// 使用appsetting.json配置文件
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="fileDir"></param>
        /// <returns></returns>
        public static IHostBuilder UseAppJson(this IHostBuilder builder, string fileDir = null)
        {
            builder.ConfigureAppConfiguration(configuration => configuration.UseAppJson(fileDir));
            return builder;
        }

        /// <summary>
        /// 使用独立的JSON配置文件
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="fileDir"></param>
        public static IConfigurationBuilder UseAppJson(this IConfigurationBuilder configuration, string fileDir = null)
        {
            var environmentVariable = EnvConstant.GetEnv();//环境变量值
            if (!string.IsNullOrEmpty(environmentVariable))
            {
                var keyValuePair = new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, environmentVariable);//构建环境变量字典
                configuration.AddInMemoryCollection(new List<KeyValuePair<string, string>>() { keyValuePair });//设置环境变量配置
            }

            if (string.IsNullOrEmpty(fileDir))
            {
                //默认读取根目录配置
                fileDir = AppContext.BaseDirectory;
            }

            FileDir = fileDir;//绑定文件路径
            FileName = string.IsNullOrEmpty(environmentVariable) ? $"appsettings.json" : $"appsettings.{environmentVariable}.json";//绑定配置文件名称
            Configuration = ComJsonConf.GetJsonConfiguration(FileDir, FileName);
            return configuration;
        }
    }
}